const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');

const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const adminRouter = require('./routes/admin');
const uploadRouter = require('./routes/upload');
const studentRouter = require('./routes/studet');
const app = express();

/**
 * 聊天室端口监听
 */
// var server=app.listen(5200)
// var io=require('socket.io').listen(server);
// io.on('connection',(socket)=>{
//   console.log('连接成功')
//
//   socket.on('message',data=>{
//      console.log(data)
//   })
// })

const webSocketService = require('./sockets/socket')

webSocketService.listen()

//***************************************

app.all('*',function (req,res,next) {
  //设置跨域的域名，*代表允许任意域名跨域
  res.header('Access-Control-Allow-Origin',"*");

  //允许的header类型
  res.header('Access-Control-Allow-Headers','*');

  //跨域允许的请求方式
  res.header("Acess-Control-Allow-Methods","*");
  if(req.method.toLowerCase()=='options')
    res.send(200);
  else
    next();
})
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/admin',adminRouter);
app.use('/upload',uploadRouter);
app.use('/student',studentRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
